package com.dkd.day202511;

import com.dkd.day20250614.ListNode;

public class Solution3 {
    //将两个升序链表合并为一个新的 升序 链表并返回。新链表是通过拼接给定的两个链表的所有节点组成的。
    public static void main(String[] args) {

    }

    public static ListNode mergeTwoLists(ListNode list1, ListNode list2) {
        if (list1 == null) return list2;
        if (list2 == null) return list1;

        ListNode head = null;
        ListNode pre = null;
        while (list1 != null && list2 != null) {
            if (list1.val < list2.val) {
                if (pre == null) {
                    head = list1;
                    pre = list1;
                    list1 = list1.next;
                }else{
                    pre.next = list1;
                    pre = pre.next;
                    list1 = list1.next;
                }
            }else{
                if (pre == null) {
                    head = list2;
                    pre = list2;
                    list2 = list2.next;
                }else {
                    pre.next = list2;
                    pre = pre.next;
                    list2 = list2.next;
                }
            }
        }
        //判断是否有遗漏
        if (list1 == null && list2 != null) {pre.next = list2;}
        if (list1 != null && list2 == null) {pre.next = list1;}
        return head;
    }
}
